import React, { memo, useEffect, useState } from "react";
import type { FC, ReactNode } from "react";
import { ListeningPageWrapper } from "./style";
import storage from "@/utils/Storage";
import { useAppDispatch, useAppSelector } from "@/store";
import { feachUserPlayHistoryAction } from "@/views/musicLibrary/store";
import classNames from "classnames";
import { shallowEqual } from "react-redux";
import AreaItemv3 from "@/components/area-itemv3";

interface IProps {
  children?: ReactNode;
}

const ListeningPage: FC<IProps> = () => {
  // 控制是 历史播放和最近播放
  const [type, setType] = useState(1)
  // 控制当前选择的 历史tab栏
  const [currIndex, setCurrIndex] = useState(0)

  const dispatch = useAppDispatch()
  useEffect(() => {
    const userId = storage.get("data").user.userId
    dispatch(feachUserPlayHistoryAction({ id: userId, type }))
  }, [dispatch, type])

  const historyTabs = [
    { type: 1, text: "最近一周" },
    { type: 0, text: "历史播放" }
  ]

  const handleHistory = (index: number, type: number) => {
    setCurrIndex(index)
    setType(type)
  }

  const { playHistorys } = useAppSelector((state) => ({
    playHistorys: state.musicLibrary.playHistorys
  }), shallowEqual)

  return <ListeningPageWrapper>
    <div className="header-tabs">
      {
        historyTabs.map((item, index) => (
          <div className={classNames("history-item", { historyActive: currIndex === index })} onClick={() => handleHistory(index, item.type)} key={item.type}>{item.text}</div>
        ))
      }
    </div>
    <div className="litenting-coniner">
      {playHistorys.length > 0 &&
        playHistorys.map(item => (
          <AreaItemv3 key={item.song.id} itemData={item.song} playCount={item.playcount} />
        ))}
    </div>
  </ListeningPageWrapper>;
};

export default memo(ListeningPage);